import { useState } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import ImageUpload from '@/components/common/ImageUpload';
import SimpleRichTextEditor from '@/components/common/SimpleRichTextEditor';
import { cn } from '@/lib/utils';
import { useNews, useCreateNews, useUpdateNews, useDeleteNews } from '@/hooks/useNews';
import { useQueryClient } from '@tanstack/react-query';
import { News, NewsCreate, NewsUpdate } from '@/types';

// 新闻分类选项
const NEWS_CATEGORIES = [
  { value: '', label: '所有分类' },
  { value: '公司新闻', label: '公司新闻' },
  { value: '项目动态', label: '项目动态' },
  { value: '行业动态', label: '行业动态' },
  { value: '技术分享', label: '技术分享' },
];


export default function NewsManagement() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentNews, setCurrentNews] = useState<News | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('all'); // 'all', 'published', 'draft'

  const queryClient = useQueryClient();

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    excerpt: '',
    content: '',
    cover_image: '',
    category: '公司新闻',
    is_published: true
  });

  // 使用API hooks
  const { data: newsData, isLoading, error } = useNews({
    keyword: searchTerm,
    category: categoryFilter,
    page: 1,
    size: 50
  });
  const createNewsMutation = useCreateNews();
  const updateNewsMutation = useUpdateNews();
  const deleteNewsMutation = useDeleteNews();

  // 筛选新闻
  const filteredNews = (newsData?.items || []).filter(news => {
    // 状态筛选
    if (statusFilter === 'published' && !news.is_published) return false;
    if (statusFilter === 'draft' && news.is_published) return false;
    return true;
  });

  // 根据value获取分类标签
  function getCategoryLabel(value: string): string {
    const category = NEWS_CATEGORIES.find(cat => cat.value === value);
    return category ? category.label : '';
  }

  // 根据标签获取分类value
  function getCategoryValue(label: string): string {
    const category = NEWS_CATEGORIES.find(cat => cat.label === label);
    return category ? category.value : '';
  }
  
  // 打开添加新闻模态框
  const openAddModal = () => {
    setIsEditing(false);
    setCurrentNews(null);
    setFormData({
      title: '',
      excerpt: '',
      content: '',
      cover_image: '',
      category: '公司新闻',
      is_published: true
    });
    setIsModalOpen(true);
  };
  
  // 打开编辑新闻模态框
  const openEditModal = (newsItem: News) => {
    setIsEditing(true);
    setCurrentNews(newsItem);
    setFormData({
      title: newsItem.title,
      excerpt: newsItem.excerpt || '',
      content: newsItem.content,
      cover_image: newsItem.cover_image || '',
      category: newsItem.category || '公司新闻',
      is_published: newsItem.is_published || false
    });
    setIsModalOpen(true);
  };
  
  // 关闭模态框
  const closeModal = () => {  
    setIsModalOpen(false);
  };
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    const checked = 'checked' in e.target ? e.target.checked : false;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };
  
  // 处理图片上传成功
  const handleImageUpload = (url: string) => {
    setFormData(prev => ({
      ...prev,
      cover_image: url
    }));
  };

  // 处理图片上传错误
  const handleImageUploadError = (error: string) => {
    toast.error(error);
  };
  
  // 保存新闻（添加或编辑）
  const saveNews = async (isDraft = false) => {
    if (!formData.title || !formData.excerpt || !formData.content) {
      toast.error('请填写标题、摘要和内容');
      return;
    }

    // 如果是发布状态，封面图片必填
    if (!isDraft && formData.is_published && !formData.cover_image) {
      toast.error('发布新闻需要上传封面图片');
      return;
    }

    try {
      if (isEditing && currentNews) {
        // 编辑现有新闻
        const updateData: NewsUpdate = {
          title: formData.title,
          excerpt: formData.excerpt,
          content: formData.content,
          cover_image: formData.cover_image,
          category: formData.category,
          is_published: isDraft ? false : formData.is_published
        };

        await updateNewsMutation.mutateAsync({
          id: currentNews.id,
          data: updateData
        });
        toast.success('新闻更新成功');
      } else {
        // 添加新闻
        const createData: NewsCreate = {
          title: formData.title,
          excerpt: formData.excerpt,
          content: formData.content,
          cover_image: formData.cover_image,
          category: formData.category,
          is_published: isDraft ? false : formData.is_published
        };

        await createNewsMutation.mutateAsync(createData);
        toast.success('新闻添加成功');
      }

      closeModal();
    } catch (error) {
      toast.error(isEditing ? '新闻更新失败' : '新闻添加失败');
    }
  };
  
  // 删除新闻
  const deleteNews = async (id: number) => {
    if (window.confirm('确定要删除这篇新闻吗？')) {
      try {
        await deleteNewsMutation.mutateAsync(id);
        toast.success('新闻删除成功');
      } catch (error) {
        toast.error('新闻删除失败');
      }
    }
  };

  // 切换新闻状态
  const toggleNewsStatus = async (id: number) => {
    const newsItem = filteredNews.find(item => item.id === id);
    if (!newsItem) return;

    const newStatus = !newsItem.is_published;
    const statusText = newStatus ? '发布' : '草稿';

    try {
      await updateNewsMutation.mutateAsync({
        id,
        data: {
          is_published: newStatus
        }
      });

      // 强制刷新新闻列表数据
      queryClient.invalidateQueries({
        queryKey: ['news'],
        exact: false
      });

      // 如果当前筛选状态会导致新闻消失，自动切换到"全部状态"
      if ((statusFilter === 'published' && !newStatus) ||
          (statusFilter === 'draft' && newStatus)) {
        setStatusFilter('all');
        toast.success(`新闻已设为${statusText}！为了让您看到更新后的新闻，已自动切换到"全部状态"视图`, {
          duration: 4000
        });
      } else {
        toast.success(`新闻已设为${statusText}`);
      }
    } catch (error) {
      toast.error('状态更新失败');
    }
  };
  
  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-exclamation-triangle text-3xl text-red-600 mb-4"></i>
            <p className="text-gray-600">加载新闻数据失败</p>
          </div>
        </div>
      </AdminLayout>
    );
  }
  
  return (
    <AdminLayout>
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">新闻管理</h1>
          <p className="text-gray-600">
            管理公司新闻和动态内容
            <span className="ml-4 text-sm">
              <span className="text-green-600">已发布: {(newsData?.items || []).filter(n => n.is_published).length}</span>
              <span className="ml-3 text-orange-600">草稿: {(newsData?.items || []).filter(n => !n.is_published).length}</span>
            </span>
          </p>
        </div>
        <button
          type="button"
          onClick={openAddModal}
          className="mt-4 md:mt-0 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center"
        >
          <i className="fa-solid fa-plus mr-2"></i> 添加新闻
        </button>
      </div>
      
      {/* 搜索和筛选 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="relative flex-grow max-w-md">
            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            <input
              type="text"
              placeholder="搜索新闻标题或摘要..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            />
          </div>
          <div className="flex items-center gap-4">
            <div className="w-full md:w-auto">
              <select
                value={categoryFilter}
                onChange={(e) => setCategoryFilter(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                aria-label="选择分类"
              >
                {NEWS_CATEGORIES.map(category => (
                  <option key={category.value} value={category.value}>{category.label}</option>
                ))}
              </select>
            </div>
            <div className="w-full md:w-auto">
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                aria-label="选择状态"
              >
                <option value="all">全部状态</option>
                <option value="published">已发布</option>
                <option value="draft">草稿箱</option>
              </select>
            </div>
            <button
              type="button"
              onClick={() => {
                setSearchTerm('');
                setCategoryFilter('');
                setStatusFilter('all');
              }}
              className="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg transition-colors"
            >
              <i className="fa-solid fa-refresh mr-1"></i> 重置
            </button>
          </div>
        </div>
      </div>
      
      {/* 新闻列表 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图片</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredNews.length > 0 ? (
                filteredNews.map((newsItem) => (
                  <tr key={newsItem.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{newsItem.id}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="w-24 h-24 rounded overflow-hidden">
                        <img
                          src={newsItem.cover_image}
                          alt={newsItem.title}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm font-medium text-gray-900 max-w-xs">{newsItem.title}</div>
                      <div className="text-sm text-gray-500 line-clamp-2 mt-1">{newsItem.excerpt}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                        {newsItem.category}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                          newsItem.is_published
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {newsItem.is_published ? '发布' : '草稿'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{newsItem.created_at}</td><td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        type="button"
                        onClick={() => toggleNewsStatus(newsItem.id)}
                        className={`mr-3 text-sm ${
                          newsItem.is_published
                            ? 'text-yellow-600 hover:text-yellow-900'
                            : 'text-green-600 hover:text-green-900'
                        }`}
                      >
                        {newsItem.is_published ? '设为草稿' : '发布'}
                      </button>
                      <button
                        type="button"
                        onClick={() => openEditModal(newsItem)}
                        className="text-blue-600 hover:text-blue-900 mr-3 text-sm"
                      >
                        编辑
                      </button>
                      <button
                        type="button"
                        onClick={() => deleteNews(newsItem.id)}
                        className="text-red-600 hover:text-red-900 text-sm"
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="px-6 py-10 text-center text-gray-500">
                    <div className="flex flex-col items-center">
                      <i className="fa-solid fa-newspaper text-4xl mb-3 text-gray-300"></i>
                      <p>暂无新闻数据</p>
                      <button
                        type="button"
                        onClick={openAddModal}
                        className="mt-2 text-blue-600 hover:text-blue-900 text-sm"
                      >
                        添加新闻
                      </button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        
        {/* 分页控件 */}
        {filteredNews.length > 0 && (
          <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
            <div className="text-sm text-gray-700">
              显示 <span className="font-medium">1</span> 到 <span className="font-medium">{filteredNews.length}</span> 条，共 <span className="font-medium">{filteredNews.length}</span> 条记录
            </div>
            <div className="flex space-x-2">
              <button type="button" className="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50" disabled>
                <i className="fa-solid fa-chevron-left text-xs"></i>
              </button>
              <button type="button" className="px-3 py-1 border border-gray-300 rounded-md bg-blue-50 text-blue-600 hover:bg-blue-100">1</button>
              <button type="button" className="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50" disabled>
                <i className="fa-solid fa-chevron-right text-xs"></i>
              </button>
            </div>
          </div>
        )}
      </div>
      
      {/* 新闻添加/编辑模态框 */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-lg w-full max-w-4xl max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-gray-800">{isEditing ? '编辑新闻' : '添加新闻'}</h3>
                <button
                  type="button"
                  onClick={closeModal}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>
            </div>
            
            <div className="p-6">
              <form>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div className="md:col-span-2">
                    <label htmlFor="title" className="block text-gray-700 font-medium mb-2">
                      标题 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="title"
                      name="title"
                      value={formData.title}
                      onChange={handleInputChange}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入新闻标题"
                    />
                  </div>
                  
                  <div className="md:col-span-2">
                    <label htmlFor="excerpt" className="block text-gray-700 font-medium mb-2">
                      摘要 <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id="excerpt"
                      name="excerpt"
                      value={formData.excerpt}
                      onChange={handleInputChange}
                      rows={2}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入新闻摘要（将显示在新闻列表页）"
                    ></textarea>
                  </div>
                  
                  <div className="md:col-span-2">
                    <label htmlFor="content" className="block text-gray-700 font-medium mb-2">
                      内容 <span className="text-red-500">*</span>
                    </label>
                    <SimpleRichTextEditor
                      value={formData.content}
                      onChange={(content) => setFormData(prev => ({ ...prev, content }))}
                      placeholder="请输入新闻详细内容..."
                      height={400}
                    />
                  </div>
                  
                  <div className="md:col-span-1">
                    <label className="block text-gray-700 font-medium mb-2">
                      封面图片 <span className="text-red-500">*</span>
                    </label>
                    <ImageUpload
                      value={formData.cover_image}
                      onChange={handleImageUpload}
                      onError={handleImageUploadError}
                      width={256}
                      height={256}
                      maxSize={5}
                      placeholder="点击或拖拽上传新闻封面"
                      autoCompress={true}
                    />
                    <p className="text-xs text-gray-500 mt-2">
                      封面图片将显示在新闻列表中，建议尺寸: 600x400px，支持 JPG、PNG、WebP 格式，最大 5MB
                    </p>
                    <p className="text-xs text-blue-600 mt-1">
                      💡 文章内的图片请在上方富文本编辑器中直接插入
                    </p>
                  </div>
                  
                  <div className="md:col-span-1">
                    <label htmlFor="category" className="block text-gray-700 font-medium mb-2">
                      分类 <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="category"
                      name="category"
                      value={formData.category}
                      onChange={handleInputChange}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    >
                      {NEWS_CATEGORIES.filter(cat => cat.value !== '').map(category => (
                        <option key={category.value} value={category.value}>{category.label}</option>
                      ))}
                    </select>
                    
                    <div className="mt-6">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          name="is_published"
                          checked={formData.is_published}
                          onChange={handleInputChange}
                          className="form-checkbox h-5 w-5 text-blue-600 rounded"
                        />
                        <span className="ml-2 text-gray-700">发布新闻</span>
                      </label>
                      <p className="text-xs text-gray-500 mt-1">未勾选将保存为草稿</p>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            
            <div className="p-6 border-t flex justify-between">
              <button
                type="button"
                onClick={closeModal}
                className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <div className="flex space-x-3">
                <button
                  type="button"
                  onClick={() => saveNews(true)}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                >
                  <i className="fa-solid fa-save mr-2"></i>
                  保存为草稿
                </button>
                <button
                  type="button"
                  onClick={() => saveNews(false)}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                >
                  <i className="fa-solid fa-paper-plane mr-2"></i>
                  {isEditing ? '更新并发布' : '发布新闻'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
